# -*- coding: utf-8 -*-
"""
--------------------------------------------
    Author:  niuqt
    Date:  8/1/2022 
--------------------------------------------
"""

# 查询所有用户数据

import os
import time

from django.conf import settings

from django.core.paginator import Paginator
from django.http import JsonResponse

from app01 import models


# 查询所有数据
def select(request):
    nowPage = request.GET.get("page")
    limit = request.GET.get("limit")
    if limit == "":
        limit = 5

    alluser_list = models.UserInfo.objects.values()
    paginator = Paginator(list(alluser_list), int(limit))
    # print(list(alluser_list))
    if int(nowPage) >= int(paginator.num_pages):
        nowPage = paginator.num_pages
    try:
        page = paginator.page(nowPage)
    except:
        page = paginator.page(paginator.num_pages)

    data = {'data': list(page), 'code': "200", 'count': paginator.count, 'page': page.number, 'limit': page.__len__(),
        'pages': paginator.num_pages

    }
    return JsonResponse(data)  # 返回所有的数据，和每页显示多好行，以及页数的设置


# 添加用户
def adduserclass(request):
    if request.method == 'POST':
        user_email = request.POST.get("user_email", None)  # 获取html传过来的值
        user_name = request.POST.get("user_name", None)
        user_is_active = request.POST.get("user_is_active", None)
        user_is_superuser = request.POST.get("user_is_superuser", None)
        user_password = request.POST.get("user_password", None)

        if models.UserInfo.objects.create_user(email=user_email, username=user_name, is_active=user_is_active,
                                               is_superuser=user_is_superuser, password=user_password):
            return JsonResponse({"code": 200, "msg": "添加成功"}, safe=False)
        else:
            return JsonResponse({"code": 300, "msg": "添加失败"}, safe=False)


# 删除用户，通过传过来的用户 id，进行删除
def deleteuser(request):
    user_id = request.GET.get("id", None)
    # print(sno)
    if models.UserInfo.objects.filter(pk__in=[1, int(user_id)]).delete():
        return JsonResponse({"code": 200, "msg": "删除成功"}, safe=False)
    else:
        return JsonResponse({"code": 300, "msg": "添加失败"}, safe=False)


# 修改用户
def edituser(request):
    if request.method == 'POST':

        user_name = request.POST.get("user_name", None)
        user_email = request.POST.get("user_email", None)
        user_is_active = request.POST.get("user_is_active", None)
        user_is_superuser = request.POST.get("user_is_superuser", None)
        userid = request.POST.get("userid", None)

        # print(user_name,user_email,user_is_active,user_is_superuser,userid)

        # id ,为表中的字段名，这个要注意
        if models.UserInfo.objects.filter(id=userid).update(email=user_email, username=user_name,
                                                            is_active=user_is_active, is_superuser=user_is_superuser):

            return JsonResponse({"code": 200, "msg": "添加成功"}, safe=False)
        else:
            return JsonResponse({"code": 300, "msg": "添加失败"}, safe=False)


# 模糊查询用户
def search(request):
    user_email = request.GET.get("user_email")
    user_name = request.GET.get("user_name")
    nowPage = request.GET.get("page")
    limit = request.GET.get("limit")

    # print(user_email,user_name)
    if limit == "":
        limit = 5

    if user_email != "":
        user_list = models.UserInfo.objects.values().filter(email__contains=user_email)
    if user_name != "":
        user_list = models.UserInfo.objects.values().filter(username__contains=user_name)
    paginator = Paginator(list(user_list), int(limit))

    if int(nowPage) >= int(paginator.num_pages):
        nowPage = paginator.num_pages
    try:
        page = paginator.page(nowPage)
    except:
        page = paginator.page(paginator.num_pages)
    data = {'data': list(page), 'code': "200", 'count': paginator.count, 'page': page.number, 'limit': page.__len__(),
        'pages': paginator.num_pages

    }
    return JsonResponse(data)


# 批量删除
def user_delete_all(request):
    # 先判断发过来的是否是post请求
    if request.method == "POST":
        # 得到要删除的ids列表 值
        values = request.POST.getlist('ids')

        # 好像传过来的 values  是 ['3,5,7']  这样的形式，我们需要进一步的细化
        # print(values[0])
        # print(type(values[0]))
        # print(values[0].split(','))
        # print(type(values[0].split(',')))

        new_list = values[0].split(',')
        # print(new_list)

        for i in range(len(new_list)):
            # 如果id不为空，获取该字段，并将其删除，我们只删除book表，publisher表不变
            deleteID = int(new_list[i])
            book_obj = models.UserInfo.objects.get(id=deleteID)
            book_obj.delete()
        # 删除成功返回显示页
        # return redirect('/curd/')
        data = {

            'code': "200",

        }
        return JsonResponse(data)


# 添加屏蔽装饰器
from django.views.decorators.csrf import csrf_exempt


@csrf_exempt
def fileadd(request):
    import csv
    if request.method == 'POST':
        file = request.FILES.get('file')
        # print(file.name)
        new_time = time.strftime('%Y_%m_%d_%H_%M_%S', time.localtime())
        # 在文件名前面加上时间
        file.name = new_time + file.name
        excel_type = file.name.split('.')[1]
        if excel_type in ['csv']:
            media_root = settings.MEDIA_ROOT
            filepath = os.path.join(media_root, file.name)
            with open(filepath, 'wb') as fp:
                for chunk in file.chunks():
                    fp.write(chunk)
            with open(filepath, newline='', encoding='GBK') as f:
                f_csv = csv.reader(f)
                headers = next(f_csv)

                for row in f_csv:
                    models.UserInfo.objects.create_user(username=row[0], email=row[1], is_active=row[2],
                        is_superuser=row[3], password=row[4])
            data = {'code': "200", }
            return JsonResponse(data)


# 个人修改
def peruserclass(request):
    if request.method == 'POST':
        user_email = request.POST.get("user_email", None)  # 获取html传过来的值
        user_name = request.POST.get("user_name", None)
        user_password = request.POST.get("user_password", None)
        userid = request.POST.get("userid", None)

        # print(user_name,user_email,user_password,userid)

        # id ,为表中的字段名，这个要注意
        if models.UserInfo.objects.filter(id=userid).update(email=user_email, username=user_name,
                                                            password=user_password):
            # 因为auth的password是加密的，所以这里要 重新给密码字段加密下，这样才可以让用户正常登陆
            user_name_temp = models.UserInfo.objects.get(id=userid)
            user_name_temp.set_password(user_password)
            user_name_temp.save()

            return JsonResponse({"code": 200, "msg": "修改成功"}, safe=False)
        else:
            return JsonResponse({"code": 300, "msg": "修改失败"}, safe=False)
